package utils

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

type Configuration struct {
	Address      string
	ReadTimeout  int64
	WriteTimeout int64
	Version      string
	Dsn          string
	AppId        string
	AppSecret    string
	PkgName      string
	Key          string
	RedTime      string
	Rds          string
	RedLimit     int
	RedLock      bool
}

type ReturnData struct {
	Errcode int         `json:"errcode"`
	Errmsg  string      `json:"errmsg"`
	Data    interface{} `json:"data"`
}

var Config Configuration
var Logger *log.Logger

func init() {

	// 加载配置文件
	loadConfig()

	// 获取log句柄
	file, err := os.OpenFile("utils/"+Config.PkgName+"-server.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Println("failed to open log file", err)
	}
	Logger = log.New(file, "INFO ", log.Ldate|log.Ltime|log.Lshortfile)
}

func loadConfig() {
	// 打开一个句柄
	var config string
	env := os.Getenv("LENV")
	switch env {
	case "develop":
		config = "config_dev.json"
	case "product":
		config = "config_pro.json"
	case "lsb":
		config = "config_lsb.json"
	case "test":
		config = "config_test.json"
	default:
		config = "config_dev.json"
	}

	file, err := os.Open("utils/" + config)
	if err != nil {
		log.Println("configs file cannot be opened"+config, err)
	}
	decoder := json.NewDecoder(file)
	Config = Configuration{}
	err1 := decoder.Decode(&Config)
	if err1 != nil {
		log.Println("cannot get configuration from json file", err1)
	}
}

func P(a ...interface{}) {
	fmt.Println(a)
}

func Version() string {
	return Config.Version
}

func Info(args ...interface{}) {
	Logger.SetPrefix("INFO ")
	Logger.Println(args...)
}

func Error(args ...interface{}) {
	Logger.SetPrefix("ERROR ")
	Logger.Println(args...)
}

func Warning(args ...interface{}) {
	Logger.SetPrefix("WARNING ")
	Logger.Println(args...)
}

func CreateUUID() (uuid string) {
	u := new([16]byte)
	_, err := rand.Read(u[:])
	if err != nil {
		log.Println("Cannot generate UUID", err)
	}

	// 0x40 is reserved variant from RFC 4122
	u[8] = (u[8] | 0x40) & 0x7F
	// Set the four most significant bits (bits 12 through 15) of the
	// time_hi_and_version field to the 4-bit version number.
	u[6] = (u[6] & 0xF) | (0x4 << 4)
	uuid = fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
	return
}

func (returndata *ReturnData) Returnfunc(write http.ResponseWriter) {
	write.Header().Set("Access-Control-Allow-Origin", "http://192.168.0.101:3000") // 允许访问所有域
	write.Header().Set("Access-Control-Allow-Credentials", "true")
	write.Header().Add("Access-Control-Allow-Headers", "Content-Type") // header的类型
	write.Header().Set("content-type", "application/json")             // 返回数据格式是json
	res, _ := json.Marshal(returndata)
	io.WriteString(write, string(res))
	return
}

func CheckErr(write http.ResponseWriter, err error, code int, msg string) {
	if err != nil {
		// 记录日志  不用可关闭
		Error(code, err, msg)

		// api返回错误
		returnDa := ReturnData{
			Errcode: code,
			Errmsg:  msg,
		}
		returnDa.Returnfunc(write)
	}
}
